package cn.com.bluemoon.daps.notice.template;

import cn.com.bluemoon.daps.common.toolkit.BmAssetUtils;
import cn.com.bluemoon.daps.common.validation.JValidUtils;
import cn.com.bluemoon.daps.notice.template.base.BaseMessage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 统一处理消息内容
 *
 * @author Jarod.Kong
 * @date 2021/6/11 11:05
 */
@Slf4j
public abstract class AbstractTemplate {
    private final BaseMessage templateMsg;
    @Setter
    private boolean validateTemplateMsg;

    protected AbstractTemplate(BaseMessage templateMsg) {
        validateTemplateMsg = true;
        this.templateMsg = templateMsg;

    }

    /**
     * 允许重写
     *
     * @return
     */
    protected File baseFileDir() {
        URL url = Thread.currentThread().getContextClassLoader().getResource("templates");
        if (url != null) {
            return new File(url.getFile());
        }
        url = this.getClass().getClassLoader().getResource("templates");
        if (url != null) {
            File file = new File(url.getFile());
            return file;
        }
        ClassPathResource cls = new ClassPathResource("templates");
        try {
            return cls.getFile();
        } catch (IOException e) {
            return new File("/templates");
        }
    }

    /**
     * @return 根据baseMessage#的模板生成内容
     */
    public String getTemplateContent() {
        final BaseMessage message = templateMsg;
        validateMsg(message);
        BmAssetUtils.notNull(message);
        String msgTemplatePath = message.getMsgTemplatePath();
        try {
            Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
            cfg.setClassForTemplateLoading(AbstractTemplate.class, "/templates");
            cfg.setDefaultEncoding("UTF-8");
            cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
            cfg.setLogTemplateExceptions(false);
            cfg.setWrapUncheckedExceptions(true);
            BmAssetUtils.notNull(msgTemplatePath, "走freemaker模板生成html必须指定模板名，路径取/templates");
            Template template = cfg.getTemplate(msgTemplatePath);
            Map<String, Object> model = new HashMap<>();
            model.put("params", message);
            String text = FreeMarkerTemplateUtils.processTemplateIntoString(template, model);
            return text;
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void validateMsg(BaseMessage templateMsg) {
        if (validateTemplateMsg) {
            List<String> validate = JValidUtils.INSTANCE.validate(templateMsg);
            BmAssetUtils.isTrue(validate.isEmpty(), "消息内容校验不通过, 如下：" + String.join(System.lineSeparator(), validate));
        }
    }

    public BaseMessage getTemplateMsg() {
        return templateMsg;
    }
}
